/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙，邂逅框架梦]
 * 
 * https://zhiqim.org/project/zhiqim_framework/zhiqim_ui.htm
 *
 * Zhiqim UI is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
 
+(function(Z)
{
//BEGIN

/****************************************/
//定义Z.Uploadmult下的原型属性和方法
/****************************************/
Z.Uploadmult = Z.Class.newInstance();
Z.Uploadmult.prototype = 
{
    defaults:
    {
        elem: null,
        contextPath: null,
        onPreview: null,
        onCompleted: null,
        fileFormatExt: "image/png,image/jpeg,image/jpg,image/gif",
    },
    
    execute: function()
    {
        this.$elem = Z.$elem(this.elem, "Z.Uploadmult");
        this.random = Z.random(10);
        this.text = this.$elem.text();
        
        this.$file = Z("<input id='Z_Uploadmult_"+this.random+"' type='file' accept='"+this.fileFormatExt+"' class='z-hide' multiple>");
        this.$file.appendTo("body").change(this.onFileOpenWindow, this);
    
        this.$elem.click(function(){this.clear();this.$file[0].click();}, this);
    },
    
    onFileOpenWindow: function()
    {//打开文件选择窗口
        this.files = this.$file[0].files;
        this.fileResults = [];
        
        if (!Z.T.isFunction(this.onPreview))
        {//不用预览直接上传
            this.upload();
        }
        else
        {//预览
            this.results = [];
            this.onFileLoad();
        }
    },
    
    onFileLoad: function()
    {//加载文件
        var file = this.files[this.results.length];
        var reader = new FileReader();  
        reader.onload = Z.bind(function(e)
        {
            this.results.push({name: file.name, type: file.type, size: file.size, lastModified: file.lastModified, lastModifiedDate: file.lastModifiedDate, src: e.target.result});
            if (this.results.length == this.files.length)
                this.onPreview(this.results);
            else
                this.onFileLoad();
        }, this);
        reader.readAsDataURL(file);
    },
    
    onFileRemove: function(e)
    {//删除文件事件
        var $remove = Z(Z.E.current(e));
        var name = $remove.attr("name");
        
        for (var i=0;i<this.results.length;i++)
        {
            var result = this.results[i];
            if (result.name == name)
            {
                this.results.splice(i, 1);
                break;
            }
        }
        
        //刷新预览
        this.onPreview(this.results);
    },
    
    isUploadFile: function(name)
    {
        for (var i=0;i<this.results.length;i++)
        {
            var result = this.results[i];
            if (result.name == name)
                return true;
        }
        return false;
    },
    
    upload: function()
    {
        this.$elem.text("正在上传");
        this.fileResults = [];
        this.fileNo = 0;
        this.uploadNext();
    },
    
    uploadNext: function()
    {
        var file = this.files[this.fileNo];
        if (!this.isUploadFile(file.name))
        {
            this.complete();
            return;
        }
        
        this.request = new XMLHttpRequest();
        this.request.open("POST", Z.rootPath(this.contextPath, "/service/upload"), true);
        this.request.setRequestHeader("Content-Type", file.type);
        this.request.setRequestHeader("Content-Length", file.size);
        if (this.fileDir)
            this.request.setRequestHeader("X-Upload-File-Dir", Z.encode(this.fileDir));
        this.request.setRequestHeader("X-Upload-File-Name", Z.encode(file.name));
        this.request.onreadystatechange = Z.bind(this.onUploadSuccess, this);
        this.request.onerror = Z.bind(this.onUploadError, this);
        this.request.send(file);
    },
    
    complete: function()
    {
        if (this.fileNo < this.files.length-1)
        {//还没上传完
            this.fileNo++;
            this.uploadNext();
        }
        else
        {//最后一个
            this.$elem.text(this.text);
            if (Z.T.isFunction(this.onCompleted))
                this.onCompleted(this.fileResults);
                
            this.clear();
        }
    },
    
    onUploadError: function()
    {
        this.fileResults.push({success: null, error: "文件上传连接服务器失败："+this.request.responseText});
        this.complete();
    },
    
    onUploadSuccess: function()
    {
        if (this.request.readyState != 4)
            return;
        
        switch(this.request.status)
        {
        case 404:this.fileResults.push({success: null, error: "文件上传时服务器不支持"});break;
        case 403:this.fileResults.push({success: null, error: "文件上传时被服务器拒绝"});break;
        case 412:this.fileResults.push({success: null, error: "文件上传时服务器诊断参数格式错误"});break;
        case 400:this.fileResults.push({success: null, error: "文件上传时服务器诊断参数传值错误"});break;
        case 200:
        {
            var fileUrl = this.request.getResponseHeader("X-Upload-File-Url");
            if (!fileUrl)
            {
                this.fileResults.push({success: null, error: "文件上传时服务器异常"});
                break;
            }
            
            this.fileResults.push({success: fileUrl, error: null});
            break;
        }
        default:this.fileResults.push({success: null, error: "文件上传时服务器未知错误："+this.request.status});break;
        }
        
        this.complete();
    },
    
    buildPreviewHtml: function(parentId)
    {//生成定制的预览内容
        var $parent = Z("#"+parentId).html("");
        for (var i=0;i<this.results.length;i++)
        {
            var $preview = Z("<div class='z-relative-left z-bg-gray' style='margin:5px;width:130px;height:130px;'></div>");
            $preview.append("<div class='z-absolute z-w100p z-h20 z-lh20 z-color-white z-text-center z-text-ellipsis' style='bottom:0;left:0;background-color:#333;' title='"+this.results[i].name+"&nbsp;（"+(Math.floor(this.results[i].size/1024))+"K）'>"+this.results[i].name+"&nbsp;（"+(Math.floor(this.results[i].size/1024))+"K）</div>");
            $preview.append("<img src='"+this.results[i].src+"' style='max-width:100%;max-height:100%;'>");
            
            var $remove = Z("<div>").appendTo($preview);
            $remove.css({position: "absolute", top: 2, right: 2, cursor: "pointer"})
                    .attr("name", this.results[i].name)
                    .html("<span class='z-px16 z-lh16 z-color-red'>×</span>")
                    .click(this.onFileRemove, this);
            
            $parent.append($preview);
        }
    },
    
    clear: function()
    {//清理
        this.$file[0].value = null;
    
        this.files = null;
        this.results = null;
        this.fileResults = null;
    },
    
    /***********************************************************************************/
    //设置方法
    /***********************************************************************************/
    
    setFileDir: function(fileDir)
    {//设置上传的目录
        this.fileDir = fileDir;
        return this;
    },
    
    setFileFormatExt: function(fileFormatExt)
    {//设置上传的格式，如image/*
        this.fileFormatExt = fileFormatExt;
        return this;
    }
};

//END
})(zhiqim);